<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-15
 * @Time: 15:22
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： SpecialColumn.php
 */
namespace app\api\model\special;

use app\common\model\teacher\Teacher;
use think\Db;
use think\Model;

/**
 * Class SpecialColumn
 * @package app\api\model
 *
 * @property mixed column_id
 * @property mixed column_title
 * @property mixed column_description
 * @property mixed column_cover
 * @property json covers
 * @property mixed column_detail
 * @property mixed column_teacher
 * @property mixed column_price
 * @property mixed column_sales
 * @property mixed column_createtime
 * @property mixed column_updatetime
 * @property mixed column_status
 * @property integer num_subscribed  订阅数
 * @property float sales_volume   总销售额
 * @property integer feed   自定义的订阅数
 *
 * Extension
 * @property bool free
 */
class SpecialColumn extends Model {
    protected $table = 'special_column';
    protected $pk = 'column_id';

    public function isFree() {
        return 0 == $this->column_price;
    }

    /**
     * is_free
     * 专栏是否收费
     *
     * @author zhengkai
     * @date 20180529
     *
     * @param $id
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function is_free($id){
        $data = self::get($id);
        if ($data->column_price>0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * getPrice
     * 获取专栏价格
     *
     * @author zhengkai
     * @date 2018-03-15
     *
     * @param int $id 专栏id
     * @return float|mixed
     */
    public static function getPrice($id) {
        $data = self::get(function ($query) use (&$id) {
            $query->where('column_id', $id);
        });

        $now = time();
        if ($data->column_sales > 0) {
            $sales = Db::table('sales')
                ->where('sales_id', $data->column_sales)
                ->where(function($query)use ($now){
                    $query->where('sales_start_time', '<', $now)
                        ->where('sales_end_time', '>', $now);
                })
                ->find();
            switch ($sales['sales_type']) {
                case 1: // 折扣
                    $data->column_price = round((((int)$sales['sales_discount']/100)*$data->column_price), 2);
                    break;
                case 2: // 减免金额
                    $data->column_price = ($data->column_price-$sales['sales_amount']);
                    break;
            }
        }

        return $data->column_price;
    }

    /**
     * getColumn
     * 获取专栏栏目数据
     *
     * @author zhengkai
     * @date 2018-01-15
     *
     * @param $uid
     * @param int $page 当前页数
     * @param int $limit 每页获取数据条数
     * @return array
     */
    public function getColumn($uid, $page=1, $limit=10)
    {
        $list=$this->getList($page, $limit);
        foreach ($list as $col) {

            $col->free = $col->isFree();

            // 专栏价格处理
            if ($col->column_sales>0 && $col->column_sales!=3) $col->column_price = self::getPrice($col->column_id);

            // 栏目更新时间处理
            if (empty($col->column_updatetime)) {
                $col->column_updatetime = tranTime($col->column_createtime);
            } else {
                $col->column_updatetime = tranTime($col->column_updatetime);
            }

            $col->column_description = stripHtml($col->column_description);
            $col->column_subscribe_status = UserSubscribeSpecial::isBuy($uid, $col->column_id);

            // 专栏自定义订阅数小于实际订阅数时显示实际订阅数
            $col->column_subscribe_total = countDataNum(UserSubscribeSpecial::totalSubscribe($col->column_id), $col->feed, true);
            $col->expiry_day = UserSubscribeSpecial::countDay($uid, $col->column_id);

            unset($col->column_createtime, $col->feed);
        }

        return $list;
    }

    public function getList($page=1, $limit=10){
        $list = self::all(function($query) use (&$page, &$limit) {
            $query->where('column_status', 0)
                ->field('column_id, column_title, column_description, covers->>\'list\' as column_cover, column_price, column_sales, column_expiry, column_createtime,
                 column_updatetime, num_subscribed, feed, sales_volume, apple_pay_price, apple_pay_production_id')
                ->order('column_createtime desc')
                ->page($page, $limit);
        });
        return $list;
    }

    /**
     * getSingleColumn
     * 获取指定id的单个专栏栏目数据
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param int $uid 用户id
     * @param int $scid 栏目id
     * @return null|static
     */
    public function getSingleColumn($uid, $scid)
    {
        $data = $this::get(function ($query) use (&$scid) {
           $query->field(
               'column_id, column_title, column_description, covers->>\'detail\' as column_cover, column_detail, column_price, column_expiry,column_sales,
                num_subscribed column_subscribe_total, feed, sales_volume, apple_pay_price, apple_pay_production_id,
               t.id as teacher_id, t.realname as teacher_name, t.avatar as teacher_avatar, td.name as teacher_degree'
           )
               ->where('column_id', $scid)
               ->join('teacher t', 'column_teacher=t.id', 'left')
               ->join('teacher_degree td', 't.degree_id=td.id', 'left');
        });

        if ($data) {
            $data->column_description = stripHtml($data->column_description);
            $data->free = $data->isFree();
            $data->column_subscribe_status = UserSubscribeSpecial::isBuy($uid, $data->column_id);

            // 专栏自定义订阅数小于实际订阅数时显示实际订阅数
            $data->column_subscribe_total = countDataNum(UserSubscribeSpecial::totalSubscribe($data->column_id), $data->feed, true);

            // 优惠促销数据处理 =====
            $now = time();
            $sales_val = 0; // 活动优惠
            $sales_list = []; // 商品赠送
            if ($data->column_sales > 0) {
                $sales = Db::table('sales')
                    ->where('sales_id', $data->column_sales)
                    ->where(function($query)use ($now){
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();

                // 赠送商品
                $giveGoods = json_decode($sales['gifts'], true);

                switch ($sales['sales_type']) {
                    case 1: // 折扣
                        if (count($giveGoods)) {
                            $giveArr = [];
                            $courseArr = [];
                            $columnArr = [];
                            foreach ($giveGoods as $key=>$val) {
                                switch ($key) {
                                    case 'curricula': // 赠送课程
                                        // 获取赠送课程数据
                                        $courseId = implode(',', $val);
                                        $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                        foreach ($giveCourse as &$course_val) {
                                            $course_val['item_type'] = 1;
                                            $courseArr[] = $course_val;
                                        }
                                        break;
                                    case 'columns': // 赠送专栏
                                        // 获取赠送专栏数据
                                        $columnId = implode(',', $val);
                                        $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                        foreach ($giveCourse as &$cloumn_val) {
                                            $cloumn_val['item_type'] = 3;
                                            $columnArr[] = $cloumn_val;
                                        }
                                        break;
                                }
                                $giveArr = array_merge($courseArr, $columnArr);
                            }
                            // 处理赠品数据
                            foreach ($giveArr as $sl_key=>$sl_val) {
                                $sl_val['sales_content'] = 2;
                                $sl_val['sales_tag'] = '赠品';
                                $sl_val['sales_info'] = '';
                                $sales_list[] = $sl_val;
                            }

                            // 折扣数据
                            $discount =  [
                                [
                                    'sales_content' => 1,
                                    'sales_tag' => '折扣',
                                    'sales_info' => round(((int)$sales['sales_discount']/10), 1).'折'
                                ]
                            ];

                            $sales_list = array_merge($discount, $sales_list);
                        } else {
                            $sales_list = [
                                [
                                    'sales_content' => 1,
                                    'sales_tag' => '折扣',
                                    'sales_info' => round(((int)$sales['sales_discount']/10), 1).'折'
                                ]
                            ];
                        }

                        $sales_val = ((int)$sales['sales_discount']/10).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $data->column_price = round((((int)$sales['sales_discount']/100)*$data['column_price']), 2);
                        break;
                    case 2: // 减免金额
                        if (count($giveGoods)) {
                            $giveArr = [];
                            $courseArr = [];
                            $columnArr = [];
                            foreach ($giveGoods as $key=>$val) {
                                switch ($key) {
                                    case 'curricula': // 赠送课程
                                        // 获取赠送课程数据
                                        $courseId = implode(',', $val);
                                        $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                        foreach ($giveCourse as &$course_val) {
                                            $course_val['item_type'] = 1;
                                            $courseArr[] = $course_val;
                                        }
                                        break;
                                    case 'columns': // 赠送专栏
                                        // 获取赠送专栏数据
                                        $columnId = implode(',', $val);
                                        $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                        foreach ($giveCourse as &$cloumn_val) {
                                            $cloumn_val['item_type'] = 3;
                                            $columnArr[] = $cloumn_val;
                                        }
                                        break;
                                }
                                $giveArr = array_merge($courseArr, $columnArr);
                            }
                            // 处理赠品数据
                            foreach ($giveArr as $sl_key=>$sl_val) {
                                $sl_val['sales_content'] = 2;
                                $sl_val['sales_tag'] = '赠品';
                                $sl_val['sales_info'] = '';
                                $sales_list[] = $sl_val;
                            }

                            // 折扣数据
                            $discount =  [
                                [
                                    'sales_content' => 1,
                                    'sales_tag' => '减免',
                                    'sales_info' => '-￥'.$sales['sales_amount']
                                ]
                            ];

                            $sales_list = array_merge($discount, $sales_list);
                        } else {
                            $sales_list = [
                                [
                                    'sales_content' => 1,
                                    'sales_tag' => '减免',
                                    'sales_info' => '-￥'.$sales['sales_amount']
                                ]
                            ];
                        }

                        $sales_val = '-￥'.$sales['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $data->column_price = ($data->column_price-$sales['sales_amount']);
                        break;
                    case 3:
                        if (count($giveGoods)) {
                            $giveArr = [];
                            $courseArr = [];
                            $columnArr = [];
                            foreach ($giveGoods as $key=>$val) {
                                switch ($key) {
                                    case 'curricula': // 赠送课程
                                        // 获取赠送课程数据
                                        $courseId = implode(',', $val);
                                        $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                        foreach ($giveCourse as &$course_val) {
                                            $course_val['item_type'] = 1;
                                            $courseArr[] = $course_val;
                                        }
                                        break;
                                    case 'columns': // 赠送专栏
                                        // 获取赠送专栏数据
                                        $columnId = implode(',', $val);
                                        $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                        foreach ($giveCourse as &$cloumn_val) {
                                            $cloumn_val['item_type'] = 3;
                                            $columnArr[] = $cloumn_val;
                                        }
                                        break;
                                }
                                $giveArr = array_merge($courseArr, $columnArr);
                            }

                            // 处理赠品数据
                            foreach ($giveArr as $sl_key=>$sl_val) {
                                $sl_val['sales_content'] = 2;
                                $sl_val['sales_tag'] = '赠品';
                                $sl_val['sales_info'] = '';
                                $sales_list[] = $sl_val;
                            }
                        }

                        $sales_val = '赠品';
                        break;
                }
            }

            $data->column_sales_list = $data->column_sales?$sales_list:[];
            $data->column_sales = $data->column_sales?$sales_val:0;
            // 优惠促销数据处理 =====

            unset($data->feed);

            // 获取最新专栏文章
            $article = new SpecialArticle();
            $data['column_new_article'] = $article->getArticle($data->column_id, 1, 5);

            $data['column_share_url'] = self::shareUrl($data['column_id']);
        }

        return $data;
    }

    /**
     * getBaseColumn
     * 获取指定id的单个专栏栏目基本信息数据
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param int $scid 栏目id
     * @param string $coverType 栏目封面图片类型：list=列表封面图片 detail=详情封面图片
     * @param int $uid 用户id
     * @return null|static
     */
    public static function getBaseColumn($scid, $coverType='list', $uid=0)
    {
        $data = self::get(function ($query) use (&$scid, &$coverType) {
            $query->field('column_id, column_title, column_description, covers->>\''.$coverType.'\' as column_cover, column_teacher, column_price, column_sales, column_expiry, column_createtime,
             column_updatetime, apple_pay_price, apple_pay_production_id, feed')
                ->where('column_id', $scid);
        });

        if (empty($data)) return null;

        $data->free = $data->isFree();
        $data->column_description = stripHtml($data->column_description);
        $data->expiry_day = UserSubscribeSpecial::countDay($uid, $data->column_id);

        // 专栏价格处理
        if ($data->column_sales>0 && $data->column_sales!=3) $data->column_price = self::getPrice($data->column_id);

        // 栏目更新时间处理
        if (empty($data->column_updatetime)) {
            $data->column_updatetime = tranTime($data->column_createtime);
        } else {
            $data->column_updatetime = tranTime($data->column_updatetime);
        }

        return $data;
    }

    public static function shareUrl($id) {
        $url = sprintf('%s/specialColumn?column_id=%d',config('server.wapHost'),$id);
        return $url;
    }


    /**
     * getRecommendColumn
     * 获取推荐的专栏数据
     * @todo 暂时为订阅最多的
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return array|false|string|static[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getRecommendColumn($limit=3)
    {
        $data = self::all(function ($query) use ($limit){
            $query->alias('sc');
            $query->join('teacher t', 'sc.column_teacher=t.id', 'left');
            $query->where('sc.column_status', 0);
            $query->field('sc.column_id, sc.column_title, sc.covers->>\'detail\' as column_cover, sc.num_subscribed, sc.column_price, sc.column_sales, sc.column_expiry, sc.feed, t.id as teacher_id, t.realname as teacher_realname, t.avatar as teacher_avatar');
            $query->order('sc.column_createtime desc');
            $query->limit($limit);
        });

        foreach ($data as &$val) {
            $val['num_subscribed'] = countDataNum(UserSubscribeSpecial::totalSubscribe($val['column_id']), $val['feed'], true);

            $val['teacher_avatar'] = $val['teacher_avatar']?:Teacher::DEFAULT_AVATAR;

            $val['is_free'] = $val['column_price']>0?0:1;

            // 优惠活动处理
            $now = time();
            if ($val['column_sales'] > 0) {
                $sales = Db::table('sales')
                    ->where('sales_id', $val['column_sales'])
                    ->where(function ($query) use ($now) {
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();

                switch ($sales['sales_type']) {
                    case 1: // 折扣
                        $val['column_price'] = round((((int)$sales['sales_discount']/100)*$val['column_price']), 2);
                        break;
                    case 2: // 减免金额
                        $val['column_price'] = ($val['column_price']-$sales['sales_amount']);
                        break;
                }
            }

            unset($val['feed'], $val['column_sales']);
        }

        $data = array_sort($data, 'num_subscribed', 'desc');
        $data = array_slice($data, 0, 3);

        return $data;
    }

    /**
     * getTeacherColumn
     * 获取指定老师的专栏数据
     *
     * @author zhengkai
     * @date 2018-04-24
     *
     * @return array|false|string|static[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getTeacherColumn($teacherId)
    {
        $data = self::all(function ($query) use ($teacherId) {
            $query->alias('c');
            $query->join('teacher t', 'c.column_teacher=t.id', 'left');
            $query->where('c.column_status', 0);
            $query->where('c.column_teacher', $teacherId);
            $query->field('c.column_id, c.column_title, c.covers->>\'list\' as column_cover, c.num_subscribed, c.column_price, c.column_sales, c.column_expiry, c.feed, t.id as teacher_id, t.realname as teacher_realname, t.avatar as teacher_avatar');
            $query->order('c.column_createtime desc');
        });

        foreach ($data as &$val) {
            $val['num_subscribed'] = countDataNum(UserSubscribeSpecial::totalSubscribe($val['column_id']), $val['feed'], true);
            $val['teacher_realname'] = $val['teacher_realname']?:Teacher::DEFAULT_AVATAR;

            // 优惠活动处理
            $now = time();
            if ($val['column_sales'] > 0) {
                $sales = Db::table('sales')
                    ->where('sales_id', $val['column_sales'])
                    ->where(function ($query) use ($now) {
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();

                switch ($sales['sales_type']) {
                    case 1: // 折扣
                        $val['column_price'] = round((((int)$sales['sales_discount']/100)*$val['column_price']), 2);
                        break;
                    case 2: // 减免金额
                        $val['column_price'] = ($val['column_price']-$sales['sales_amount']);
                        break;
                }
            }

            unset($val['feed'], $val['column_sales']);
        }

        return $data;
    }

    public static function columns($where,$field='*'){
        return self::where($where)->field($field)->find();
    }
}